using System.Linq;
using System.Windows.Controls.Primitives;

namespace System.Windows.Controls
{
    internal class TreeHolder : Grid
    {
        public TreeHolder()
        {
            _button.Template =
                ResourceHelper.GetXamlResource<ControlTemplate>(
                    "System.Windows.Controls.Primitives.ToggleButtonControlTemplate.xaml");
            _button.Checked += (sender, e) =>
                                   {
                                       if (_item == null) return;
                                       _item.IsExpanded = true;
                                   };
            _button.Unchecked += (sender, e) =>
                                     {
                                         if (_item == null) return;
                                         _item.IsExpanded = false;
                                     };

            SetColumn(_button, 1);
            Children.Add(_button);
            ColumnDefinitions.Add(_placeHolderColumn);
            ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});

            Update();
        }

        private readonly ColumnDefinition _placeHolderColumn = new ColumnDefinition();

        private readonly ToggleButton _button = new ToggleButton();

        private TreeGridItem _item;

        public TreeGridItem Item
        {
            get { return _item; }
            set
            {
                if (_item == value) return;
                Deattach();
                _item = value;
                Attach();
            }
        }

        private void Attach()
        {
            if (_item == null) return;
            _item.Expanded += ItemExpanded;
            _item.Collapsed += ItemCollapsed;
            Update();
        }

        private void ItemCollapsed(object sender, RoutedEventArgs e)
        {
            _button.IsChecked = false;
        }

        private void ItemExpanded(object sender, RoutedEventArgs e)
        {
            _button.IsChecked = true;
        }

        private void Deattach()
        {
            if (_item == null) return;
            _item.Expanded -= ItemExpanded;
            _item.Collapsed -= ItemCollapsed;
        }

        public void Update()
        {
            if (_item == null) return;
            var isLeaf = !_item.Items.Any(e => !e.IsHidden);
            _button.Visibility = isLeaf
                                     ? Visibility.Collapsed
                                     : Visibility.Visible;
            _placeHolderColumn.Width =
                new GridLength(5 + _item.Level*TreeGrid.HolderWidthPerLevel +
                               (isLeaf ? 20 : 0));
            _button.IsChecked = _item.IsExpanded;
        }
    }
}